package com.example.ovulationperiodtracker.fragment;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.ovulationperiodtracker.Allactivity.HuaiYunActivity;
import com.example.ovulationperiodtracker.databinding.FragmentMain2Binding;
import com.example.ovulationperiodtracker.utils.CalendarUtils;
import com.example.ovulationperiodtracker.utils.MyLog;
import com.example.ovulationperiodtracker.view.FirstSetDialog;
import com.example.ovulationperiodtracker.view.JingStartEndDialog;
import com.example.ovulationperiodtracker.view.NoteUtils;
import com.necer.base.BaseFragment;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

public class MainFragment2 extends BaseFragment<FragmentMain2Binding> {


    @Override
    public FragmentMain2Binding createBinding(LayoutInflater inflater, ViewGroup container) {
        return FragmentMain2Binding.inflate(inflater);
    }


    @Override
    protected void onCreated() {


        binding.txtData.setText(LocalDate.now().toString());

        binding.llHuaiyun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(context, HuaiYunActivity.class));
            }
        });

        binding.llActionSTART.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new JingStartEndDialog(context, "经期开始").setOnClickYesNoListener(new JingStartEndDialog.OnClickYesNoListener() {
                    @Override
                    public void onClickYes(LocalDate localDate) {
                        NoteUtils.DayNote dayNote = NoteUtils.getDayNote(localDate);
                        dayNote.jingStart = 1;
                        NoteUtils.saveDayNote(dayNote);

                        resetData();
                    }
                }).show();
            }
        });

        binding.llActionEND.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new JingStartEndDialog(context, "经期结束").setOnClickYesNoListener(new JingStartEndDialog.OnClickYesNoListener() {
                    @Override
                    public void onClickYes(LocalDate localDate) {
                        NoteUtils.DayNote dayNote = NoteUtils.getDayNote(localDate);
                        dayNote.jingEnd = 1;
                        NoteUtils.saveDayNote(dayNote);
                        resetData();
                    }
                }).show();
            }
        });


        int jingLength = NoteUtils.getJingLength();
        LocalDate lastJingStart = NoteUtils.getLastJingStart();
        if (lastJingStart == null || jingLength == 0) {
            new FirstSetDialog(context)
                    .setOnClickYesNoListener(new FirstSetDialog.OnClickYesNoListener() {
                        @Override
                        public void onClickYes(LocalDate localDate, int jingLength, int periodLength) {
                            NoteUtils.DayNote dayNote = NoteUtils.getDayNote(localDate);
                            dayNote.jingStart = 1;
                            NoteUtils.saveDayNote(dayNote);

                            NoteUtils.saveJingLength(jingLength);
                            NoteUtils.savePeriodLength(periodLength);


                            resetData();
                        }
                    }).show();

        } else {
            resetData();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        resetData();
    }

    public void resetData() {


        //第一次打开防止onResume中数据加载
        int jingLength = NoteUtils.getJingLength();
        LocalDate lastJingStart = NoteUtils.getLastJingStart();
        if (lastJingStart == null || jingLength == 0) {
            return;
        }

        //检查是否有预产期，如果有则走 怀孕的逻辑
        LocalDate yuChanQi = NoteUtils.getYuChanQi();
        if (yuChanQi == null) { //经期逻辑

            binding.topHuaiyun.setVisibility(View.GONE);
            binding.llMain.setVisibility(View.VISIBLE);

            binding.llActionSTART.setVisibility(View.GONE);
            binding.llActionEND.setVisibility(View.GONE);

            //经期数据
            List<LocalDate> jingData = CalendarUtils.getJingData();

            LocalDate today = LocalDate.now();

            LocalDate nextJingStart = null;

            NoteUtils.DayNote dayNote = NoteUtils.getDayNote(LocalDate.now());

            if (jingData.contains(LocalDate.now()) && dayNote.jingEnd != 1) {
                //正在经期
                long daysDifference = ChronoUnit.DAYS.between(lastJingStart, LocalDate.now());
                binding.tvDays.setText(Math.abs(daysDifference) + 1 + "");
                binding.tvDesc.setText("经期(天)");
                binding.llActionEND.setVisibility(View.VISIBLE);

                //正在经期中，判断距离几天大于10天为下一个月经开始日
                nextJingStart = jingData.stream()
                        .filter(date -> today.plusDays(10).isBefore(date))
                        .min(LocalDate::compareTo).orElse(today);

            } else {
                //不在经期，则下一个最近的日期为下次经期开始
                nextJingStart = jingData.stream()
                        .filter(date -> today.isBefore(date))
                        .min(LocalDate::compareTo).orElse(today);

                long daysDifference = ChronoUnit.DAYS.between(nextJingStart, LocalDate.now());
                binding.tvDays.setText(Math.abs(daysDifference) + "");
                binding.tvDesc.setText("下次经期(天)");
                binding.llActionSTART.setVisibility(View.VISIBLE);


            }
            binding.tvNextJing.setText(nextJingStart.toString());

            //排卵日 下次月经日-14天（黄体期），易孕日是排卵日前5天和后4天 共10天
            int huangTiQi = NoteUtils.getHuangTiQi();
            LocalDate paiLuanRi = nextJingStart.plusDays(-huangTiQi);
            ArrayList<LocalDate> paiLuanRis = new ArrayList<>();
            paiLuanRis.add(paiLuanRi);
            List<LocalDate> yiYunRis = CalendarUtils.getYiYunRi(paiLuanRis);
            if (yiYunRis.contains(today)) {
                binding.tvYiyun.setText("今天");
            } else {
                LocalDate nextYiYun = yiYunRis.stream()
                        .filter(date -> today.isBefore(date))
                        .min(LocalDate::compareTo).orElse(today);
                binding.tvYiyun.setText(nextYiYun.toString());
            }

        } else {
            // 怀孕，迎接宝宝
            binding.topHuaiyun.setVisibility(View.VISIBLE);
            binding.llMain.setVisibility(View.GONE);
            binding.llActionSTART.setVisibility(View.GONE);
            binding.llActionEND.setVisibility(View.GONE);

            long daysDifference = ChronoUnit.DAYS.between(LocalDate.now(), yuChanQi);
            if (daysDifference < 0) {
                daysDifference = 0;
            }
            binding.tvDays.setText(Math.abs(daysDifference) + "");
            binding.tvDesc.setText("迎接宝宝（天）");
        }

    }
}
